define('utils/Lazyload', null, function() {

/**
 * new Lazyload(wrapper).once(someFun);
 */
function Lazyload(wrapper) {
    this.wrapper = wrapper;
    this.doc = this.wrapper.ownerDocument;
    this.win = this.doc.defaultView;
    this.winHeight = this.win.innerHeight;
    this.needScroll = 0;
    this.callback = null;
}
Lazyload.prototype = {
    constructor: Lazyload,
    getPos: function(elem) {
        if( !elem.getClientRects().length ) {
            return { top: 0, left: 0 };
        }

        let rect = elem.getBoundingClientRect();

        let doc = elem.ownerDocument;
        let docElem = doc.documentElement;
        let win = doc.defaultView;

        return {
            top: rect.top + win.pageYOffset - docElem.clientTop,
            left: rect.left + win.pageXOffset - docElem.clientLeft
        };
    },
    run: function() {
        if(null !== this.callback) {
            this.callback();

            this.callback = null;
        }
    },
    init: function() {
        let _self = this;
        let pos = this.getPos(this.wrapper);
        this.needScroll = pos.top - this.winHeight;

        if(this.needScroll <= 0) {
            this.run();

            return;
        }

        let h = () => {
            let scrollTop = _self.doc.documentElement.scrollTop;
            if(scrollTop > _self.needScroll) {
                _self.run();
                _self.win.removeEventListener('scroll', h);
            }
        };

        this.win.addEventListener('scroll', h);
    },
    once: function(callback) {
        this.callback = callback;

        this.init();
    }
};

return Lazyload;
});
